import React from 'react'
// ===================================================================== icons
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import Encrypt from '@com/plugins/encrypt'
// ===================================================================== image
import Logo from '@img/logo.png'
import Bg from '@img/login/bg.png'
// ===================================================================== declare
const { $fn, $http, $Lazy} = window
// ===================================================================== Component
const Form 		= $Lazy.hook(()=>import('@antd/form/layout/form'))
const FormItem 	= $Lazy.load(()=>import('@antd/form/layout/item'))
const Button 	= $Lazy.load(()=>import('@antd/button'))
const Input 	= $Lazy.load(()=>import('@antd/form/input'))
const Select 	= $Lazy.load(()=>import('@antd/form/select'))
const Checkbox 	= $Lazy.load(()=>import('@antd/form/checkbox'))
// const DatePicker= $Lazy.load(()=>import('@antd/form/datePicker'))
const Progress 	= $Lazy.load(()=>import('@antd/progress'))
const message 	= $Lazy.file(()=>import('@antd/message'))
//
const AddLast 	= $Lazy.load(()=>import('@cpt/add-last'))
const Image 	= $Lazy.load(()=>import('@tp/image'))
//
const Page 		= $Lazy.load(()=>import('#tp/content/content-page'))
// 
// const $cache 	= $Lazy.file(()=>import('#private/cache-api'))
//
const ModPassword = $Lazy.state(()=>import('#private/pages/mod-password'))
// ===================================================================== config declare
const iconStyle= { color:'#999' }
const size = 'large'
const mt = 20
let clear
// ===================================================================== component
class Login extends React.Component{
	state = {
		data:[],
		selectLoading: true,
		percent:0,
		checked:true,
		yearData: [{name: '2022-至今', value: '0'}, {name: '2020-2022', value: '1'}]
	}
	
	componentDidMount(){
		
	}
	
	componentWillUnmount(){
		clearTimeout(clear)
	}
	
	onRemember = async change => {
		// 读取记住的密码
		const m = $fn.longSave('remember')
		
		if ($fn.hasObject(m)) {
			for(var i in m){ m[i] = Encrypt.decode(m[i]) }
			m['year'] = '0'	// 年份默认选中当前
		}
		
		if(window.globalConfig.companySelect){
			// 获取公司列表
			$http.pull(this,'company/select', { loading:true, token:false }).then(data=>{
				$fn.dataSave('company/select', data)
				if($fn.hasObject(m)){
					this.setState({checked:true})
					if(this.form){
						this.form.setValue(m)
						if(change){
							this.form.reset(['company'])
						}
					}
				}
			})
		}else{
			if($fn.hasObject(m)){
				this.setState({checked:true})
				if(this.form){
					this.form.setValue(m)
				}
			}
		}
		
		// 清空密码
		if( $fn.query('mod') ){ this.clearPwd() }
	}
	
	onForm = async ref => {
		this.form = ref; 
		await this.onRemember()
		/* 2022-01-19 j+2 去除环境选择 */
		// ref.setValue({ env: window.$config.api() })
	}
	
	onError = () => {
		this.setState({loading:false})
		$fn.loading(false)
	}
	
	clearPwd = () => {
		this.form.reset(['password'])
	}
	
	onSubmit = async param => {
		this.setState({loading:true})
		$fn.loading(true,'登录中...')
		delete param.env
		const data = await $http.submit(this,'auth/login',{
			param: param,
			token: false,
			loading: false,
			onError: this.onError,
			onMsg: data => { // 强制修改密码
				data.msg && message.then(f=>f.error(data.msg))
				if(data.status === -1){
					const { uuid, time } = data.data
					// 计算超过多少未修改密码
					const days = parseInt(time / (60 * 60 * 24))
					const hours = parseInt((time % (60 * 60 * 24)) / (60 * 60))
					const minutes = parseInt((time % (60 * 60)) / 60)
					const seconds = parseInt(time % (60 / 1000))
					const overtime = { days, hours, minutes, seconds }
					
					this.setState({ uuid, overtime })
					$fn.local('user',{token:data.token})
					this.pwdRef.open()
				}
			},
			// onEnd: data => $fn.longSave('cache_time', data['cache_time'])
		})
		
		if($fn.hasObject(data)){
			// 保存 token
			$fn.local('user',data)
			// 记住密码
			if(this.state.checked){
				const model = JSON.parse(JSON.stringify(param))
				// model['year'] = model['year'].toString()
				for(var i in model){ model[i] = Encrypt.encode(model[i]) }
				$fn.longSave('remember',model)
			}else{
				$fn.longRemove('remember')
			}
			
			// 获取菜单列表
			$fn.loading(true,'获取菜单中...')
			await $http.pull(null,'menu/getallmenu',{ param:{ web_version:1 }, loading:false, onError: this.onError, onMsg:()=>{
				message.then(f=>f.warning('获取菜单失败'))
			} }).then(data=>{
				$fn.local('menu', data)
				// 权限数据处理
				// if($fn.hasArray(data)){
				// 	const arr = data.filter( v => +v.id === 34)
				// 	if(arr.length === 1){
				// 		let stack = {}
				// 		arr[0].children.forEach(v=>{
				// 			v.children.forEach(m=>{
				// 				let son = m.permisson
				// 				if($fn.hasObject(son)){
				// 					son = Object.values(son)
				// 				}
				// 				stack[m.model] = son
				// 			})
				// 		})
				// 		$fn.local('menu_permisson', stack)
				// 	}
				// }
			})
			// 获取个人信息
			$fn.loading(true,'获取个人信息中...')
			await $http.pull(null,'employee/currentuser',{loading:false, onError: this.onError, onMsg: ()=>{
				message.then(f=>f.warning('获取个人信息失败'))
			}}).then(rs=>{
				if( $fn.hasObject(rs) ){ $fn.local('user',{...data,...rs}) }
			})
			
			$fn.loading(false)
			 // 获取权限 2022-07-04  --马婷 
			$fn.loading(true,'获取权限中...')
			await $http.pull(null,'employee/currentPer',{loading:false, onError: this.onError, onMsg: ()=>{
				message.then(f=>f.warning('获取权限失败'))
			}}).then(data=>{
				if( $fn.hasObject(data) ){ $fn.local('permissions',data) }
			})
			$fn.loading(false)
			$fn.longSave('api', window.globalConfig.api)
			message.then(f=>f.success('登录成功'))
			
			const to = $fn.loginTo(true)
			
			$fn.replace(this, to ? to : '/')
		}
	}
	
	render(){
		const {  pullLoading, loading, checked, uuid, overtime, percent, data } = this.state
		return (
			<>
				<Page contentClassName='fxmc wh login' style={{background:`url(${Bg}) no-repeat center/cover`}} contentStyle={{minWidth:320}}>
					<Image src={ Logo } width={120} className='abs_lt' style={{top:10,left:10}} />
					<div className='bcf r10px rel i10' style={{width:'30%', minWidth:320, padding:'25px 30px', boxShadow:'0 0 10px #bbb'}}>
						{/* 文本 */}
						<hgroup className='tc mb25'>
							<h2 className='b f20 tc'>成都诺森医学检验有限公司</h2>
							<h3 className='f14 g9 mt15'>致力于做民众身边的健康管理专家</h3>
						</hgroup>
						{/* 表单 */}
						<Form onSubmit={this.onSubmit} onRef={this.onForm}>
							{/* 2022-01-19 j+2 去除环境选择 */}
							{/*
							<FormItem name='env' rules={[{ required:true, message:'环境不能为空'}]} mb={20}>
								<Select disabled={loading} loading={pullLoading} size={size} p='选择运行环境' bordered={false} data={window.$config._api()} onChanged={ ({ value })=>{
									if(value){
										$fn.dataClear()
										$fn.localClear()
										$fn.longSave('api', value)
										// 选择异步自动开启 [2021-8-17 10:53:17 ?F10: AM?] --伍智睿
										if (value === 'http://mapi.norsonmed.com:802/api/') {
											$fn.longSave('async', 1)
										} else {
											$fn.longRemove('async')
										}
										// window.location.reload()
										this.onRemember(true)
									}
								}}/>
							</FormItem>
							*/}
							<FormItem name='year'>
								{/*<DatePicker picker='year' disabled={loading} loading={pullLoading} size={size} p='选择年份' bordered={false} format={4} className={'login-year'} after={new Date().getFullYear()}/>*/}
								{/*<Select disabled={loading} loading={pullLoading} size={size} p='选择年份' bordered={false} data={yearData} noSearch onChanged={({value}) => {
									const { type, apis } = window.globalConfig
									window.globalConfig.api = apis[value]
								}} />*/}
							</FormItem>
							{/* 2022-02-17 动态 选择/输入 */}
							{window.globalConfig.companySelect ? <FormItem name='company' rules={[{ required:true, message:'公司不能为空'}]} mt={mt}><Select disabled={loading} loading={pullLoading} size={size} p='选择分公司' bordered={false} data={data} idStr='uuid' nameStr='company_name' noSearch onChanged={()=>{
								$fn.dataClear()
								// window.location.reload()
							}}/></FormItem> : <FormItem name='comp_num' mt={mt} rules={[{ required:true, message:'公司代码不能为空'}]}><Input disabled={loading} p='公司代码' bordered={false} prefix={<UserOutlined style={iconStyle} />} size={size} /></FormItem>}
							<FormItem name='phone' mt={mt} rules={[{ required:true, message:'用户名不能为空'}]}><Input disabled={loading} p='账号/工号/手机号/邮箱' bordered={false} prefix={<UserOutlined style={iconStyle} />} size={size} /></FormItem>
							<FormItem name='password' mt={mt} rules={[{ required:true, message:'密码不能为空' }]}><Input disabled={loading} p='密码' bordered={false} prefix={<LockOutlined style={iconStyle} />} size={size} mode='password' /></FormItem>
							<div className='mt15'><Checkbox value={checked} label='记住密码' onChange={checked=>this.setState({ checked })} disabled={loading} /></div>
							<Button full loading={loading} size={size} htmlType='submit' code='Enter' boxClassName='mt30' label='登录' onClick={()=>{this.form.submit();$fn.dataClear()}}/>
						</Form>
					</div>
					<footer className='abs_lb w tc f12 cf lh30'>
						<div className='fxmc'>
							<p className='mr20 f14'>帮助 Help</p>
							<p className='mr20 f14'>隐私 Privace</p>
							<p className='f14'>条款 Clause</p>
						</div>
						<p>copyright © 诺森检验</p>
					</footer>
				</Page>
				{/* 强制修改密码 */}
				<ModPassword 
					onRef 		= { ref => this.pwdRef = ref } 
					uuid		= { uuid }
					overtime	= { overtime }
					onClose		= { this.clearPwd }
				/>
				{/* 数据加载 */}
				{
					(percent > 0 && percent <= 100) && (
						<AddLast name='progress' isUpdate>
							<div className='abs_full fxmc' style={{background:'rgba(0,0,0,0.1)'}}>
								<div className='r10px fxmc' style={{width:300, height:300, padding:20, boxShadow:'0 0 3px #f9f9f9', background:'rgba(255,255,255,.8)'}}>
									<div>
										<div className='fxc'><Progress value={percent} /></div>
										<div className='g6 tc mt10'>数据加载中...</div>
									</div>
								</div>
							</div>
						</AddLast>
					)
				}
			</>
		)
	}
}
export default Login